package shuangzu.top.zzurla.activities;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Presentation;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.Window;
import android.widget.*;
import cn.pedant.SweetAlert.SweetAlertDialog;
import com.alibaba.fastjson.JSONObject;
import easypermission.davidinchina.com.easylibrary.EasyPermission;
import okhttp3.*;


import shuangzu.top.zzurla.R;
import shuangzu.top.zzurla.entities.entity_bulletin;
import shuangzu.top.zzurla.utils.utils_jsonstring;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static cn.pedant.SweetAlert.SweetAlertDialog.ERROR_TYPE;
import static cn.pedant.SweetAlert.SweetAlertDialog.PROGRESS_TYPE;
import static cn.pedant.SweetAlert.SweetAlertDialog.SUCCESS_TYPE;

public class login_activity extends Activity {

    private ImageView logo;
    private Button btn_login;
    private EditText txt_username;
    private EditText txt_password;
    private CheckBox login_remember;
    private String getjson_string;
    private String passwd;
    private int user_level;
    private boolean isPasswdRight=false;
    private TextView txtinfo;
    private SharedPreferences pref;
    private SharedPreferences.Editor editor;
    private boolean flagfinish;
    private SweetAlertDialog pDialog;
    private Handler handler=null;

    AlertDialog.Builder dialog;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.login_activity);
        pref= PreferenceManager.getDefaultSharedPreferences(this);
        logo=(ImageView)findViewById(R.id.logo);
        logo.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),R.drawable.ic_luncher_dabai));
        btn_login=(Button)findViewById(R.id.login_btn_login);
        txt_username=(EditText)findViewById(R.id.login_edit_account);
        txt_password=(EditText)findViewById(R.id.login_edit_pwd);
        txtinfo=(TextView)findViewById(R.id.txtshowinfo);
        login_remember=(CheckBox)findViewById(R.id.Login_Remember);
        boolean is_remember=pref.getBoolean("remember",false);
        pDialog = new SweetAlertDialog(this, PROGRESS_TYPE);
        handler=new Handler();
        if(is_remember)
        {
            String account=pref.getString("username","");
            String passwd=pref.getString("passwd","");
            txt_username.setText(account);
            txt_password.setText(passwd);
            login_remember.setChecked(true);
        }

//请求权限
        EasyPermission.with(this).code(1).permissions(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.LOCATION_HARDWARE,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.INTERNET,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
                Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.GET_ACCOUNTS,
                Manifest.permission.READ_CONTACTS,
                Manifest.permission.SYSTEM_ALERT_WINDOW
        ).request();

        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(txt_username.getText().toString().trim().length()!=0 && txt_password.getText().toString().trim().length()!=0) {
                    txtinfo.setText(txt_username.getText().toString().trim());
                    //btn_login.setText(passwd);
                    pDialog=new SweetAlertDialog(login_activity.this,PROGRESS_TYPE);
                    pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
                    pDialog.setTitleText("正在访问服务器....");
                    pDialog.setCancelable(true);
                    pDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            pDialog.dismissWithAnimation();
                        }
                    });
                    pDialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            pDialog.cancel();
                        }
                    });
                    pDialog.show();

                    flagfinish=false;
                    new Thread(){
                        public void run()
                        {
                            try {
                                //sendRequestWithOkHttp("http://server.aspi.tech:8080/zrla/user/findbyid?user_id=" + txt_username.getText().toString().trim());

                                OkHttpClient client = new OkHttpClient();
                                Request request = new Request.Builder()
                                        .url("http://server.aspi.tech:8080/zrla/user/findbyid?user_id=" + txt_username.getText().toString().trim())
                                        .get()
                                        .build();
                                Response response = client.newCall(request).execute();

                                String responseData = response.body().string();
                                txtinfo.setText(txtinfo.getText().toString().trim() + "\npwd:" + passwd + "\nlevel:" + user_level + "\n"+ responseData);

                                JSONObject jsonObject =JSONObject.parseObject(responseData);
                                passwd=jsonObject.getString("user_passwd");
                                user_level=jsonObject.getInteger("user_level");

                                isPasswdRight = txt_password.getText().toString().trim().equals(passwd);
                                if (isPasswdRight) {
                                    editor = pref.edit();
                                    if (login_remember.isChecked()) {
                                        editor.putBoolean("remember", true);

                                    } else {
                                        editor.clear();
                                    }
                                    editor.putString("username", txt_username.getText().toString());
                                    editor.putString("passwd", txt_password.getText().toString());
                                    editor.apply();
                                    Intent intent = new Intent(login_activity.this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(intent);


                                }
                                else
                                {
                                    handler.post(ui_changedialog);
                                }
                            }
                            catch (Exception e)
                            {
                                e.printStackTrace();
                            }finally {
                                flagfinish=true;
                            }



                        }
                    }.start();


                }


            }
        });

    }

    Runnable ui_changedialog=new Runnable() {
        @Override
        public void run() {
            pDialog.changeAlertType(ERROR_TYPE);
            pDialog.setTitleText("登录失败！");
            pDialog.setCancelable(true);
        }
    };

    Runnable ui_dialogdismiss=new Runnable() {
        @Override
        public void run() {
            pDialog.dismiss();
        }
    };


    private void sendRequestWithOkHttp(final String url) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String responseData = null;
        try {
            responseData = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        showResponse(responseData);

    }

    private void showResponse(final String response) {
        getjson_string=response;
        JSONObject jsonObject =JSONObject.parseObject(response);
        passwd=jsonObject.getString("user_passwd");
        user_level=jsonObject.getInteger("user_level");

        txtinfo.setText(txtinfo.getText().toString().trim() + "\npwd:" + passwd + "\nlevel:" + user_level + "\n" + response);

        isPasswdRight = txt_password.getText().toString().trim().equals(passwd);

    }
}
